<?php

namespace App\Admin\Controllers;

use Illuminate\Http\Request;
use App\AdminRole;
use App\AdminUser;
use App\AdminPermission;

class RoleController extends Controller
{
	//角色列表
    public function index(AdminUser $user)
    {
    	$roles = AdminRole::orderBy('id', 'asc')->paginate(10);
        return view('/admin/role/index', compact('roles', 'user'));
    }

    //创建角色页面
    public function create(){
        return view('/admin/role/add');
    }

    //添加角色
    public function store(){
    	//验证
        $this->validate(request(),[
            'name' => 'required|min:3|unique:admin_roles,name',
            'description' => 'required'
        ]);
        //逻辑
        AdminRole::create(request(['name', 'description']));

        //渲染
        return redirect('/admin/roles');
    }

    //角色权限
    public function permission(AdminRole $role){
    	$permissions = AdminPermission::all();
        $myPermissions = $role->permissions;
        return view('/admin/role/permission', compact('permissions', 'myPermissions', 'role'));
    }

    //储存角色权限行为
    public function storePermission(AdminRole $role){
        //验证
        $this->validate(request(),[
            'permissions' => 'required|array'
        ]);
        //逻辑
        $permissions = AdminPermission::findMany(request('permissions'));
        $myPermissions = $role->permissions;

        //要增加的
        $addPermissions = $permissions->diff($myPermissions);
        foreach ($addPermissions as $permission) {
            $user->assignRole($permission);
        }

        //要增加的
        $deletePermissions = $myPermissions->diff($permissions);
        foreach ($deletePermissions as $permission) {
            $user->deleteRole($permission);
        }

        //渲染
        return back();
    }

}
